/**
 *
 * @param  {Array} userRouter 后台返回的用户权限json
 * @param  {Array} allRouter  前端配置好的所有动态路由的集合
 * @return {Array} realRoutes 过滤后的路由
 */

export const recursionRouter = (userRouter: any[] = [], allRouter: any = []) => {
  var realRoutes: any[] = []
  allRouter.forEach((v: any, i: number) => {
    userRouter.forEach((item: any, index: number) => {
      //根据type进行对比
      if (item.type === v.type) {
        if (item.children && item.children.length > 0) {
          v.children = recursionRouter(item.children, v.children)
        }
        realRoutes.push(v)
      }
    })
  })
  return realRoutes
}

/**
*
* @param {Array} routes 用户过滤后的路由
*
* 递归为所有有子路由的路由设置第一个children.path为默认路由
*/
export const setDefaultRouter = (routes: any[]) => {
  routes.forEach((v: any, i: number) => {
    if (v.children && v.children.length > 0) {
      v.redirect = { name: v.children[0].name }
      setDefaultRouter(v.children)
    }
  })
}

//引入所有views下.vue文件
import view from '@/views/view.vue'
const modules: any = import.meta.glob("../views/**/**.vue");
/**
 * 解析路由表
 * @param routerMap 后台请求的路由表
 * @returns 系统路由
 */
export const routerFilterFunc = (routerMap: any[]) => {
  const arr: any[] = [];
  routerMap.forEach(item => {
    const obj: any = {
      ...item,
      beforeComponent: item.component
    };
    if (item.component === "layout") {
      obj.component = view
    } else {
      if (obj.children !== null && obj.children && obj.children.length) {
        obj.component = view
        obj.children = routerFilterFunc(obj.children);
      } else {
        obj.component = modules[`../views/${obj.component}.vue`];
      }
    }
    arr.push(obj);
  });
  return arr;
};